package com.ellricky.market.ui

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.andr.common.ui.fragment.BaseFragment
import com.andr.common.ui.mvp.BasePresenter
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.adapter.MarketActiveAdapter
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.new.MarketActive
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.ui.CreateActiveActivity
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewEBaseCallback
import com.ellricky.baselib.util.NewECallback
import com.ellricky.baselib.util.NewEListCallback
import com.ellricky.market.R
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import kotlinx.android.synthetic.main.market_fragment_active.*
import java.util.*

class MarketActiveFragment : BaseFragment<Void, BasePresenter<Void>>() {

    private var paramMap: HashMap<String, String> = hashMapOf()
    private var refresh = false
    private val activeType: String by lazy {
        arguments?.getString(BaseConstant.KEY_ID) ?: ""
    }
    private val marketActiveAdapter by lazy {
        MarketActiveAdapter()
    }

    companion object {
        fun newInstance(activeType: String): MarketActiveFragment {
            val fragment = MarketActiveFragment()
            val bundle = Bundle()
            bundle.putString(BaseConstant.KEY_ID, activeType)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getContentLayout(): Int {
        return R.layout.market_fragment_active
    }

    override fun initUIView(p0: View?) {
        rvActive.layoutManager = LinearLayoutManager(mContext)
        rvActive.setSwipeMenuCreator(mSwipeMenuCreator) // 菜单创建器。

        initOnClick()

        rvActive.adapter = marketActiveAdapter
    }

    override fun onResume() {
        super.onResume()
        loadData(true)
    }

    private fun initOnClick() {
        tvCreateActive.setOnClickListener {
            EAppUtil.jumpPageWithNoParam(requireActivity(), CreateActiveActivity::class.java)
        }

        rvActive.setOnItemMenuClickListener { menuBridge,
                                              adapterPosition ->
            menuBridge.closeMenu()
            val direction = menuBridge.direction // 左侧还是右侧菜单。
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                deleteActive(adapterPosition)
            }
        }
    }

    private fun deleteActive(adapterPosition: Int) {
        val data = marketActiveAdapter.get(adapterPosition)
        val activeId = data.activity_id
        val url = EAppUtil.getApiHost()

        val paramMap = hashMapOf<String, String>()
        paramMap["action"] = "deleteActivity"
        paramMap["activity_id"] = activeId.toString()
        paramMap["eid"] = LocalCacheUtil.getUid()
        HttpUtils.getInstance().postFrom(url, paramMap, object : NewECallback<Any>(mContext) {
            override fun onSuccess(data: Any?, msg: String?) {
                loadData(true)
            }
        })
    }

    private fun initParamMap() {
        paramMap["action"] = "activityList"
        paramMap["eid"] = LocalCacheUtil.getUid()
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        paramMap["activity_type"] = activeType
        paramMap["page"] = "1"
        paramMap["page_size"] = "40"
    }

    private fun loadData(refresh: Boolean) {
        this.refresh = refresh
        val url = EAppUtil.getApiHost()
        initParamMap()
        val callback: NewEBaseCallback = getResponseCallback2()
        HttpUtils.getInstance().postFrom(url, paramMap, callback)
    }

    private fun getResponseCallback2(): NewEBaseCallback {
        return object : NewEListCallback<MarketActive>(mContext) {
            override fun onSuccess(data: MutableList<MarketActive>?, msg: String?) {
                marketActiveAdapter.refresh(data)
            }
        }
    }

    /**
     * 菜单创建器。
     */
    private val mSwipeMenuCreator = SwipeMenuCreator { _, swipeRightMenu, position ->
        val width = resources.getDimensionPixelSize(com.ellricky.baselib.R.dimen.dp_70)

        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        val height = resources.getDimensionPixelSize(com.ellricky.baselib.R.dimen.dp_85)

        // 添加右侧的，如果不添加，则右侧不会出现菜单。
        val deleteItem = SwipeMenuItem(mContext)
            .setBackground(com.ellricky.baselib.R.drawable.base_bg_menu_del)
            .setText("删除")
            .setTextSize(12)
            .setTextColor(Color.WHITE)
            .setWidth(width)
            .setHeight(height)
        swipeRightMenu.addMenuItem(deleteItem)// 添加一个按钮到右侧侧菜单。
    }
}